import store from '@/store'
import { getNavData } from '@/utils/http'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/LoginView.vue'),
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/home/HomeView.vue'),
    meta: { title: '后台管理系统' },
    redirect: '/welcome',
    children: [
      {
        name: 'welcome',
        path: '/welcome',
        meta: { title: '首页' },
        component: () => import('../views/home/index/WelcomeMain.vue'),
      }
    ]
  }
]

// 防止路由重复点击报错
const originalPush = VueRouter.prototype.push;
// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  linkActiveClass: "selected",
  routes
})

//路由拦截
//挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token');
  if (token) {//是否存在token
    if (to.name == 'login') {
      next('/home');
      return
    } else {
      if (store.state.nav.length == 0) {
        addRoutes();
      }
      next();
    }
  } else {
    if (to.name == 'login') {
      next();
    } else {
      console.log("未登录，跳转登录页！");
      next('/');
    }
  }
})

let navdata = [];
//拼接数据
function routesData(result) {
  result.forEach(i => {
    // console.log(i);//后端数据的父路由
    navdata.push({
      path: i.Navpath,
      name: i.NavName,
      meta: { title: i.NavTitle },
      // icon: i.NavIcon,
      component: () => import(`../views/home/${i.NavParentPath}/${i.NavComponent}.vue`),
      children: []
    })
    i.Navchildren.forEach(f => {
      let index = navdata.findIndex(item => item.name === i.NavName);
      if (index > -1) {
        navdata[index].children.push({
          path: f.Navpath,
          name: f.NavName,
          meta: { title: f.NavTitle },
          component: () => import(`../views/home/${f.NavParentPath}/${f.NavComponent}.vue`)
        });
      }
    })
  })
  routes[2].children = navdata;
  return routes
}

function addRoutes() {
  getNavData().then(res => {
    //获取数据
    //拼接数据（路由）
    let data = routesData(res.data);
    // 减少请求，数据的缓存
    store.dispatch('SETNAV', res.data)
    //动态添加
    for (let i of data) {
      router.addRoute(i);
    }
  })
}

export default router